package com.example.compose.ui.wifi

import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresApi


class WIFIManager(val context: Context){
    private val wifiManager:WifiManager = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
    fun connectionInfo() = wifiManager.connectionInfo

    private var connectivityManager:ConnectivityManager? = null

    //从 Build.VERSION_CODES#Q 开始，不允许应用程序启用/禁用 Wi-Fi。
    fun openWifi(){
        val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    fun isWifiEnabled() = wifiManager.isWifiEnabled

    fun scanResults() = wifiManager.scanResults

    fun connect(ssid:String,password:String){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            try {
                val wifiConfig = WifiConfiguration()
                wifiConfig.SSID = ssid
                wifiConfig.preSharedKey = password
                val netId = wifiManager.addNetwork(wifiConfig)
                wifiManager.disconnect()
                wifiManager.enableNetwork(netId, true)
                wifiManager.reconnect()
                if (isWifiConnected(ssid)) {
                    Log.d("WIFIManager","WIFI$ssid 连接成功")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid(ssid)
                .setWpa2Passphrase(password)
                .build()

            val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build()

            connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

            connectivityManager?.requestNetwork(networkRequest,NetworkCallback())
        }
    }

    private fun isWifiConnected (machineID: String) : Boolean{
        if (wifiManager.isWifiEnabled) {
            val wifiInfo = wifiManager.connectionInfo
            if (wifiInfo?.ssid==machineID)
                return true
        }

        return false
    }

    @RequiresApi(Build.VERSION_CODES.M)
    inner class NetworkCallback: ConnectivityManager.NetworkCallback(){
        override fun onUnavailable() {
            super.onUnavailable()
        }

        override fun onLosing(network: Network, maxMsToLive: Int) {
            super.onLosing(network, maxMsToLive)

        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            connectivityManager?.bindProcessToNetwork(network)
        }

        override fun onLost(network: Network) {
            super.onLost(network)

        }
    }

}